<template>
  <view>
    <view class="userinfo">
      <view class="u_title">预约教练</view>
      <view class="userbox">
        <image class="hdimg" :src="userInfo.PhotoUrl" mode="aspectFill" @click="nav_to('/pages/teacher/detail?id='+userInfo.ID)"></image>
        <view class="rightbox">
          <view class="namebox">
            <view class="name">{{ $util.entitiesToUtf16(userInfo.TrueName) }}</view>
            <view class="level" :class="{ 'level': userInfo.Level == '初级' || userInfo.Level == '中级' || userInfo.Level == '高级' || userInfo.Level == '助教', 'level2': userInfo.Level == '跟拍', 'level3': userInfo.Level == '网红' }">{{ userInfo.Level }}</view>
          </view>
          <view class="r_name_2">
            <view class="ratingbox">
              <view class="rattext">评分：</view>
              <block v-for="(value, index) in starRateView(userInfo.Score)" :key="index">
                <image class="ratimg" :src="value"></image>
              </block>
            </view>
            <view class="addrebox">
              <image class="addreimg" src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/upload/17152361921951044.png">
              </image>
              <view class="placed">{{ userInfo.City || '未知' }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="details">
      <view class="d_title">预约明细</view>
      <view class="group">
        <view class="g_lift">项目名称</view>
        <view class="g_right hiddenText">{{ $util.entitiesToUtf16(skilljson.ProductName) }}</view>
      </view>
      <view class="group">
        <view class="g_lift">价格</view>
        <view class="g_right">{{ skilljson.Price + '/小时' }}</view>
      </view>
      <!-- <view class="group">
        <view class="g_lift">支付方式</view>
        <view class="inp_box" @click="showpay = true">
          <input type="text" :value="paytype" disabled placeholder="请选择" placeholder-class="platitle" />
        </view>
        <view class="icon_box">
          <uni-icons type="right" size="20" color="#333333"></uni-icons>
        </view>
      </view> -->
      <view class="group">
        <view class="g_lift">时长</view>
        <view class="inp_box" @click="showmotion = true">
          <input type="text" :value="sum" disabled placeholder="请选择" placeholder-class="platitle" />
        </view>
        <view class="icon_box">
          <uni-icons type="right" size="20" color="#333333"></uni-icons>
        </view>
      </view>
      <view class="group">
        <view class="g_lift">服务时间</view>
        <view class="inp_box" @click="showTime = true">
          <input :value="dateTime" type="text" disabled placeholder="请选择" placeholder-class="platitle" />
        </view>
        <view class="icon_box">
          <uni-icons type="right" size="20" color="#333333"></uni-icons>
        </view>
      </view>
      <view class="group">
        <view class="g_lift">运动场地</view>
        <view @click="openMap" class="inp_box flx ball_space">
          <input v-model="ShopName" type="text" disabled placeholder="请选择" placeholder-class="platitle" />
        </view>
        <view class="icon_box">
          <uni-icons type="right" size="20" color="#333333"></uni-icons>
        </view>
      </view>
      <view class="group">
        <view class="g_lift">交通费</view>
        <view class="red_right">{{ '教练到场后按照实际路程，需支付其往返路费' }}</view>
      </view>
      <view class="group">
        <view class="g_lift">备注</view>
        <view class="inp_box">
          <input v-model="remarkText" type="text" placeholder="如有特殊情况请提前告知(选填)" maxlength="50"
            placeholder-class="platitle" />
        </view>
      </view>
    </view>
    <view class="bottombtn">
      <view class="paybtn" @click="orderApp()">{{ '确认支付 ' + '￥' + sumPrice }}</view>
    </view>

    <!-- 时长选择 -->
    <u-picker :show="showmotion" immediateChange @confirm="setmotion" @cancel="showmotion = false"
      :columns="motiontype"></u-picker>
    <!-- 时间选择 -->
    <u-datetime-picker :minDate="minDate" ref="datetimePicker" :show="showTime" mode="datetime"
      @cancel="showTime = false" @confirm="setTime" :filter="timeFilter"></u-datetime-picker>
      <!-- 支付方式选择 -->
    <u-picker :show="showpay" immediateChange @confirm="setpay" @cancel="showpay = false"
      :columns="paylist"></u-picker>
  </view>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      showpay:false,
      paytype:'',
      paylist:[['立即支付','线下支付']],
      navindex:0,
      skllIndex:0,
      teId: '', // 教练ID
      skilljson: {
        ProductID: '', // 项目ID
        ProductName: '', // 项目
        Price: '', // 项目费用
        Qty: '', // 时长
      },
      userInfo: {},

      sum: '',
      ShopName: '',
      minDate: new Date().getTime(),
      showTime: false,
      remarkText:'',
      reqData: {
        TecherID: '', //教练ID
        Hours: '', // 时长
        ServerTime: '', // 服务开始时间
        Latitude: '',
        Longitude: '',
        Place: '', // 地址
        Remark: '', // 备注
        Price: 0,// 总价格
        ShopID: 1 //门店id
      },
      //时长控制
      showmotion: false,
      motiontype: [['1', '2', '3', '4','5','6','7','8']],
    };
  },
  async onLoad(e) {
    this.skllIndex = e.skillindex
    this.navindex = e.navindex
    this.reqData.TecherID = e.id
    await this.getDetail(e.id)
    this.skilljson.ProductID = e.skillid
    this.skilljson.Price = e.skillprice
  },
  onReady() {
    // 微信小程序需要用此写法
    this.$refs.datetimePicker.setFormatter(this.formatter);
  },

  computed: {
    dateTime() {
      if (!this.reqData.ServerTime) {
        return '';
      } else {
        return this.reqData.ServerTime;
      }
    },
    sumPrice() {
      this.reqData.Price = Number(this.reqData.Hours) * this.skilljson.Price
      return this.reqData.Price
    }
  },
  methods: {
    // 获取教练信息详情
    async getDetail(e = 0) {
      let id = e == 0 ? this.reqData.TecherID : e
      let res = await this.$api.post("Technicians/Detail", {
        ID: id,
      });
      const { code, data } = res;
      console.log(res, 'res');
      if (code == 0) {
        this.userInfo = data
        this.skilljson.ProductName = data.ServerList[this.navindex].ServerItemList[this.skllIndex].ProductName
        
      }
    },
    //预约订单
    async orderApp() {
      if(!this.reqData.Hours){
        this.$pv.msg('请选择时长');
				return false
      }
      if(!this.reqData.ServerTime){
        this.$pv.msg('请选择时间');
				return false
      }
      if(!this.reqData.Place){
        this.$pv.msg('请选择地址');
				return false
      }
      let data = JSON.stringify([this.skilljson])
      // data.push(JSON.stringify(this.skilljson))
      let remstring = this.$util.utf16ToEntities(this.remarkText)
      this.reqData.ItemStr = data
      this.reqData.Remark = remstring
      let apiData = { ...this.reqData }
      console.log(this.reqData, '111');
      let res = await this.$api.post('ServerOrder/Apply', apiData)
      let _this = this
      if (res.code == 0) {
        let appdata = res.data
        let pres = await this.$api.post('/Payment/PayV2', {
          EventID: appdata.EventID,
          CompanyID: 6003,
          total_fee: appdata.Pay_Total,
          EventType: appdata.EventType,
          body: appdata.Pay_Body,
          SourcePage: 'te_reserva',
          // #ifdef MP-WEIXIN
          PayChannel: "weixin",
          // #endif
          // #ifdef APP
          PayChannel: "app"
          // #endif
        })
        console.log({
           EventID: appdata.EventID,
          CompanyID: 6003,
          total_fee: appdata.Pay_Total,
          EventType: appdata.EventType,
          body: appdata.Pay_Body,
          SourcePage: 'te_reserva',
          // #ifdef MP-WEIXIN
          PayChannel: "weixin",
          // #endif
          // #ifdef APP
          PayChannel: "app"
          // #endif
        },'1111');
        
        let payObj = JSON.parse(pres.data);
        console.log(pres,'pres');
        
        uni.requestPayment({
          provider: 'wxpay',
          // #ifdef APP
          orderInfo: payObj,
          // #endif
          // #ifdef MP-WEIXIN
          timeStamp: payObj.timeStamp,
          nonceStr: payObj.nonceStr,
          package: payObj.package,
          signType: payObj.signType,
          paySign: payObj.paySign,
          // #endif
          success: async function (res) {
            _this.$pv.msg('支付成功');
            setTimeout(() => {
              _this.redirect_to('/pages/teacher/success_page?id=' + appdata.EventID)
            }, 200)

          },
          fail: async function (err) {
            console.log(err,'err');
            
            let del = await _this.$api.post('ServerOrder/Delete', {
								ID: appdata.EventID,
							});
            _this.$pv.msg('您已取消支付');
          }
        });
      }
    },
    setpay(){
      this.paytype = e.value[0]
      this.showpay = false
    },
    setmotion(e) {
      this.reqData.Hours = e.value[0];
      this.skilljson.Qty = e.value[0]
      this.sum = e.value[0] + '个小时'
      this.showmotion = false;
    },
    setTime(e) {
      this.startdate = e.value
      let em = uni.$u.timeFormat(e.value, 'hh:MM');
      let n = ''
      let b = ''
      if (em.slice(3) > 30) {
        let time = Number(e.value) + (3600 * 1000)
        n = uni.$u.timeFormat(time, 'yyyy-mm-dd');
        b = uni.$u.timeFormat(time, 'hh:MM');
      } else {
        n = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
        b = uni.$u.timeFormat(e.value, 'hh:MM');
      }
      if (b.slice(3) != 30) {
        let hm = b.split('')
        hm.splice(3, 1, '0')
        hm.splice(4, 1, '0')
        // console.log(hm, 'b');
        b = hm.join('')
      }
      this.reqData.ServerTime = n + ' ' + b;
      // this.reqData.ServerTime = b;
      // console.log(this.reqData.ServerDate, this.reqData.ServerTime.slice(3), 'this.reqData.ServerTime');
      this.showTime = false;
    },
    timeFilter(mode, options) {
      console.log(options,'11');
      
      let d = new Date()
      if (mode === 'hour') {
        let mi = d.getMinutes()
        if (mi > 30) 
        return options
      }
      if (mode === 'minute') {
        return ['00', '30']
      }
      return options;
    },
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'day') {
        return `${value}日`;
      }
      if (type === 'hour') {
        return `${value}时`;
      }
      if (type === 'minute') {
        return `${value}分  `;
      }
      return value;
    },
    //选择地址
    openMap(item) {
      const _this = this
      try {
        uni.chooseLocation({
          async success(res) {
            console.log(res, 'addres');
            let d = await _this.$util.getAddress({ longitude: res.longitude, latitude: res.latitude });
            console.log(d, 'd');
            _this.reqData.Latitude = res.latitude
            _this.reqData.Longitude = res.longitude
            _this.reqData.Place = res.name || d.result.address_reference.landmark_l2.title
            _this.ShopName = res.name || d.result.address_reference.landmark_l2.title
          },
          fail(err) {
            console.log(err, 'err');
          },
        });
      } catch (error) {
        console.log(error, 'error');
      }
    },
  },

}
</script>
<style lang='scss'>
page {
  background-color: #f6f6f6;
}

.userinfo {
  width: 702rpx;
  height: 236rpx;
  background: #FFFFFF;
  border-radius: 16rpx;
  margin: 18rpx auto;
  padding: 34rpx 24rpx;
  box-sizing: border-box;

  .u_title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
    margin-bottom: 26rpx;
  }
}

.userbox {
  display: flex;
  align-items: center;

  // margin-bottom: 20rpx;
  .hdimg {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    background-color: aqua;
  }

  .rightbox {
    margin-left: 24rpx;

    .namebox {
      display: flex;
      align-items: center;
      margin-bottom: 8rpx;

      .name {
        font-size: 36rpx;
        font-weight: bold;
        color: #333333;
        margin-right: 8rpx;
      }

      .level {
        width: 80rpx;
          // height: 32rpx;
          border-radius: 8rpx;
          background: linear-gradient(90deg, #EEC385 0%, #F8CE8A 100%);
          color: #5F4C36;
          text-align: center;
          font-size: 26rpx;
      }
      .level2 {
          width: 80rpx;
          // height: 32rpx;
          border-radius: 8rpx;
          background: linear-gradient(90deg, #FF5B67 0%, #FF5989 100%);
          color: #fff;
          text-align: center;
          font-size: 26rpx;
        }

        .level3 {
          width: 80rpx;
          // height: 32rpx;
          border-radius: 8rpx;
          background: linear-gradient(90deg, #FF951F 0%, #FF581D 100%);
          color: #fff;
          text-align: center;
          font-size: 26rpx;
        }
    }

    .r_name_2 {
      display: flex;
      align-items: center;

      .ratingbox {
        display: flex;
        align-items: center;
        margin-right: 18rpx;

        .rattext {
          font-size: 24rpx;
          color: #666666;
        }

        .ratimg {
          width: 24rpx;
          height: 24rpx;
        }
      }

      .addrebox {
        display: flex;
        align-items: center;

        .addreimg {
          width: 32rpx;
          height: 32rpx;
        }

        .placed {
          color: #666666;
          font-size: 24rpx;
        }
      }
    }
  }
}

.details {
  width: 702rpx;
  // height: 668rpx;
  background: #FFFFFF;
  border-radius: 16rpx;
  padding: 32rpx 24rpx;
  box-sizing: border-box;
  margin: 0 auto;
  margin-top: 16rpx;

  .d_title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
    margin-bottom: 40rpx;
  }

  .group {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 40rpx;

    .g_lift {
      font-size: 28rpx;
      color: #333333;
      margin-right: 20rpx;
    }

    .g_right {
      flex: 1;
      font-size: 28rpx;
      color: #333333;
      text-align: right;
    }

    .red_right {
      color: #FC4F45;
      font-size: 24rpx;
    }

    .inp_box {
      flex: 1;

      input {
        width: 100%;
        color: #333333;
        text-align: right;
        font-weight: 500;
        font-size: 28rpx;
      }

      .platitle {
        font-size: 28rpx;
        color: #999999;
      }
    }

    .icon_box {
      height: 40rpx;
      width: 40rpx;
      line-height: 40rpx;
    }
  }
}

.bottombtn {
  width: 100%;
  height: 196rpx;
  position: fixed;
  bottom: 0;
  left: 0;
  background-color: #fff;

  .paybtn {
    width: 670rpx;
    height: 88rpx;
    background: #706EEE;
    border-radius: 44rpx;
    text-align: center;
    line-height: 88rpx;
    font-size: 32rpx;
    font-weight: bold;
    color: #fff;
    margin: 0 auto;
    margin-top: 36rpx;

    // position: fixed;
    // bottom: 88rpx;
    // left: 50%;
    // transform: translateX(-50%);
  }
}
</style>